package cn.lopr.mvc.frame.util;

import cn.lopr.util.ObjectUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author shuangyang7
 * @date 2021/7/19 15:00
 */
public class MyBatisUtils {

    public static ThreadLocal<SqlSession> sqlSessionThreadLocal = new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory = null;

    public static SqlSessionFactory getSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            try {
                InputStream inputStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }

    public static <T> T getMapper(Class<T> tClass) {

        SqlSession sqlSession = getSqlSessionThreadLocal();
        if (!ObjectUtils.isEmpty(sqlSession)) {
            return sqlSession.getMapper(tClass);
        }
        sqlSession = getSqlSessionFactory().openSession(true);
        MyBatisUtils.setSqlSessionThreadLocal(sqlSession);

        return sqlSession.getMapper(tClass);
    }


    public static void setSqlSessionThreadLocal(SqlSession sqlSession) {
        sqlSessionThreadLocal.set(sqlSession);
    }

    public static SqlSession getSqlSessionThreadLocal() {
        return sqlSessionThreadLocal.get();
    }

    public static void remove() {
        getSqlSessionThreadLocal().close();
        sqlSessionThreadLocal.remove();
    }

}
